package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.configuration.AliReturnPay;
import com.example.demo.mapper.AdWalletMapper;
import com.example.demo.mapper.ClothingManageMapper;
import com.example.demo.mapper.entity.AdTransaction;
import com.example.demo.mapper.entity.Advertiser;
import com.example.demo.mapper.entity.Clothing;
import com.example.demo.service.AdWalletService;
import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdWalletServiceImpl extends ServiceImpl<AdWalletMapper, AdTransaction> implements AdWalletService {
    @Autowired
    private AdWalletMapper mapper;

    @Override
    public double selectRemainingSum(int userId) {
        return mapper.selectRemainingSum(userId);
    }

    @Override
    public void setAliRequestPay(AdTransaction transaction) {
        int userId = transaction.getAdvertiserId();
        int advertiserId = mapper.selectAdvertiser(userId);
        //项ad_transaction表插入数据
        transaction.setAdvertiserId(advertiserId);
        mapper.insert(transaction);
        //更新advertiser表数据，更新用户余额
        Advertiser advertiser = new Advertiser();
        advertiser.setUserId(userId);
        advertiser.setBalance(transaction.getAmount());
        mapper.addAmount(advertiser);
    }

    @Override
    public void setAliReturnPay(AliReturnPay aliReturnPay) {
        AdTransaction nowTransaction = mapper.selectOne(new QueryWrapper<AdTransaction>()
                .eq("out_trade_no", aliReturnPay.getOut_trade_no()));

        int transactionId = nowTransaction.getTransactionId();
        double totalAmount = Double.parseDouble(aliReturnPay.getTotal_amount());
        nowTransaction.setTradeNo(aliReturnPay.getTrade_no());

        Advertiser advertiser = new Advertiser();
        advertiser.setAdvertiserId(nowTransaction.getAdvertiserId());
        advertiser.setBalance(totalAmount);

        if(aliReturnPay.getTrade_status().equals("TRADE_SUCCESS")){
            mapper.updateById(nowTransaction);
        }else{
            mapper.deleteById(transactionId);
            mapper.minusAmount(advertiser);
        }
    }

    @Override
    public int selectAdvertiser(int userId) {
        int advertiserId =mapper.selectAdvertiser(userId);
        return advertiserId;
    }

    @Override
    public PageVo<AdTransaction> getAdTransactionList(PageBo pageBo, int advertiserId) {
        QueryWrapper<AdTransaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("advertiser_id", advertiserId);
        queryWrapper.eq("transaction_type", 1);
        List<AdTransaction> result = mapper.selectList(queryWrapper);
        return new PageVo<>(pageBo, result);
    }


}
